package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.dto.OrderReportDto;
import com.sky.dto.TurnOverReportDto;
import com.sky.dto.UserReportDto;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ReportMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkSpaceService;
import com.sky.vo.*;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.ibatis.annotations.Mapper;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.resource.HttpResource;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zcf
 */
@Service
@AllArgsConstructor
public class ResportServiceImpl implements ReportService {

    private final ReportMapper reportMapper;

    private final OrderMapper orderMapper;
    @Resource
    private UserMapper userMapper;

    @Resource
    private HttpServletResponse response;


    @Resource
    private WorkSpaceService workSpaceService;
    /**
     * 营业额统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO list(LocalDate begin, LocalDate end) {
        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        //1.获取日期列表
        List<LocalDate> dateList = begin.datesUntil(end.plusDays(1)).collect(Collectors.toList());
        List<String> stringList = dateList.stream().map(
                date -> {
                    return date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                }
        ).collect(Collectors.toList());
        String ddList = StringUtils.join(dateList, ",");

        //2.获取营业额列表
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalDateTime.MIN.toLocalTime());
        LocalDateTime endTime = LocalDateTime.of(end, LocalDateTime.MAX.toLocalTime());
        List<TurnOverReportDto> list = reportMapper.list(beginTime, endTime, Orders.COMPLETED);

        Map<String, BigDecimal> collect = list.stream().collect(Collectors.toMap(TurnOverReportDto::getOrderDate, TurnOverReportDto::getOrderMoney));
        List<BigDecimal> decimals = stringList.stream().map(
                date -> {
                    return collect.get(date) == null ? new BigDecimal("0") : collect.get(date);
                }
        ).collect(Collectors.toList());
        String join = StringUtils.join(decimals, ",");
        turnoverReportVO.setDateList(ddList);
        turnoverReportVO.setTurnoverList(join);
        return turnoverReportVO;
    }


    /**
     * 用户统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO list2(LocalDate begin, LocalDate end) {
        //1.先获取时间列表
        List<LocalDate> collect = begin.datesUntil(end.plusDays(1)).collect(Collectors.toList());
        String dateList = StringUtils.join(collect, ",");
        //2.获取时间范围内新增用户
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalDateTime.MIN.toLocalTime());
        LocalDateTime endTime = LocalDateTime.of(end, LocalDateTime.MAX.toLocalTime());
        List<UserReportDto> list = userMapper.list3(beginTime, endTime);
        Map<String, Integer> map = list.stream().collect(Collectors.toMap(UserReportDto::getDate, UserReportDto::getCount));
        List<Integer> newUserList = collect.stream().map(
                date -> {
                    return map.get(date.toString()) == null ? 0 : map.get(date.toString());
                }
        ).collect(Collectors.toList());
        String newUserListStr = StringUtils.join(newUserList, ",");
        //3.获取时间范围内总用户
        Integer count = userMapper.tatal(beginTime);
        List<Integer> totalUserList = new ArrayList<>();
        for (Integer integer : newUserList) {
            count += integer;
            totalUserList.add(count);
        }
        String totalUserListStr = StringUtils.join(totalUserList, ",");
        return UserReportVO.builder().totalUserList(totalUserListStr).newUserList(newUserListStr).dateList(dateList).build();
    }


    /**
     * 订单统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO list3(LocalDate begin, LocalDate end) {
        //1.获取时间列表
        List<LocalDate> dateList = begin.datesUntil(end.plusDays(1)).collect(Collectors.toList());
        String ddList = StringUtils.join(dateList, ",");
        //2.获取时间范围总订单列表
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalDateTime.MIN.toLocalTime());
        LocalDateTime endTime = LocalDateTime.of(end, LocalDateTime.MAX.toLocalTime());
        List<OrderReportDto> orderCountList = orderMapper.countOrders(beginTime, endTime, null);
        Map<String, Integer> map = orderCountList.stream().collect(Collectors.toMap(OrderReportDto::getDate, OrderReportDto::getCount));
        List<Integer> orderCount = dateList.stream().map(
                date -> {
                    return map.get(date.toString()) == null ? 0 : map.get(date.toString());
                }
        ).collect(Collectors.toList());
        String orderCountListStr1 = StringUtils.join(orderCount, ",");
        //3.获取有效订单数列表
        List<OrderReportDto> validOrderCountList = orderMapper.countOrders(beginTime, endTime, Orders.COMPLETED);
        Map<String, Integer> map1 = validOrderCountList.stream().collect(Collectors.toMap(OrderReportDto::getDate, OrderReportDto::getCount));
        List<Integer> validOrderCountListStr = dateList.stream().map(
                date -> {
                    return map1.get(date.toString()) == null ? 0 : map1.get(date.toString());
                }
        ).collect(Collectors.toList());
        String validOrderCountListStr1 = StringUtils.join(validOrderCountListStr, ",");
        //4.获取订单总数
        Integer total = orderCount.stream().reduce(0, Integer::sum);
        //5.获取已完成的订单数
        Integer validTotal = validOrderCountListStr.stream().reduce(0, Integer::sum);
        //6.获取订单完成率
        Double orderCompletionRate = validTotal.doubleValue() / total;
         return OrderReportVO.builder().dateList(ddList).orderCompletionRate(orderCompletionRate).orderCountList(orderCountListStr1).validOrderCountList(validOrderCountListStr1).totalOrderCount(total).validOrderCount(validTotal).build();
    }


    /**
     * 销售top10
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
       //1.查询销量前十的集合
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalDateTime.MIN.toLocalTime());
        LocalDateTime endTime = LocalDateTime.of(end, LocalDateTime.MAX.toLocalTime());
        List<GoodsSalesDTO> list = orderMapper.list4(beginTime, endTime,Orders.COMPLETED);
        String nameList = StringUtils.join(list.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList()), ",");
        String numberList = StringUtils.join(list.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList()), ",");

        return SalesTop10ReportVO.builder().nameList(nameList).numberList(numberList).build();
    }

    /**
     * 导出运营数据报表
     * @param
     */
    public void exportBusinessData() {
        //1. 查询数据库，获取营业数据---查询最近30天的运营数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);

        //查询概览数据
        BusinessDataVO businessDataVO = workSpaceService.businessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));

        //2. 通过POI将数据写入到Excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("templates/运营数据报表模板.xlsx");

        try {
            //基于模板文件创建一个新的Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);

            //获取表格文件的Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");

            //填充数据--时间
            sheet.getRow(1).getCell(1).setCellValue("时间：" + dateBegin + "至" + dateEnd);

            //获得第4行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            //获得第5行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(i);
                //查询某一天的营业数据
                BusinessDataVO businessData = workSpaceService.businessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                //获得某一行
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }

            //3. 通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}


